import React, {
    Component
} from 'react';
import {
    connect
} from 'react-redux';
import {
    getRecruitList,
    addRecruit,
    deleteRecruitList,
    changeRecruit
} from '../../store/action/recruitList.js';
import {
    timeFormat
} from '../../utils/utils';
import {
    message,
    Button,
    Modal,
    Select,
    Popconfirm,
    Input,
    DatePicker,
    Form
} from 'antd';
import './Recruitlist.css';
import {
    Link
} from 'react-router-dom';
const FormItem = Form.Item;
const {
    RangePicker
} = DatePicker;

@ connect(state => ({
    recruitList: state.recruitList.list
}))
class Recruitlist extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],//招新清单数据
            listTotal: 1,//招新信息总条数
            curPage: 0,//当前页数
            isEnough: false,//招新信息是否加载完毕
            isTeacher:false,
            loading: false,//按钮加载效果
            delArr:[],//选择删除的id数组
            visible: false,//弹框1
            visible2: false,//弹框2
            submitLoad:false,
            submitLoad2:false,
            choiceClass:[],
            choiceClass2:[],
            item2:{enrollment:{
                title:"",
                startTime:0,
                endTime:0
            },classes:[]},
            id:0
        }
    }
    componentDidMount() {
        //做身份判断
        let roleId=window.localStorage.getItem('roleId');
        if(roleId==='1'||roleId==='2')
        {
            this.setState({
                isStu:false,
                isTeacher:true
            })
        }else{
            this.setState({
                isStu:true,
                isTeacher:false
            })
        }
        this.handleGetList();   
    }

    //弹出框设置
    showModal = () => {
        this.setState({
            visible: true,
        });
    };
    showModal2 = (item) => {
        this.setState({
            visible2: true,
            item2:item,
            choiceClass2:item.classes.join(','),
            id:item.enrollment.id
        });
    };
    
    handleCancel = () => {
        this.setState({ visible: false });
    };
    handleCancel2 = () => {
        this.setState({ visible2: false });
    };

    onOk=(value)=> {
        
    }
    /**
     * 修改信息提交
     */
    handleOk2 = () => {
        this.setState({ submitLoad2: true });
        let data = this.props.form.getFieldsValue();
        let obj={
            enrollment:{
                id:0
            },
            classes:[],
        };
        if(!data.recruitName2||!data.start2[0]||!data.start2[1]||!this.state.choiceClass2[0])
        {
            message.warning("请将信息填写完整");
            this.setState({ 
                submitLoad2: false,
                choiceClass2:this.state.choiceClass2
            });
        }
        else{
        obj.enrollment.title=data.recruitName2;
        obj.enrollment.startTime=new Date(data.start2[0]).getTime()/1000;
        obj.enrollment.endTime=new Date(data.start2[1]).getTime()/1000;
        obj.classes=this.state.choiceClass2.split(',');
        obj.enrollment.id=this.state.id;
        this.props.dispatch(changeRecruit(obj));
        this.setState({ submitLoad2: false, visible2: false });
        window.location.reload();
        }
    };
    
    
    /**
     * 添加信息提交
     */
    handleSubmit=()=>{
        this.setState({ submitLoad: true });
        let data = this.props.form.getFieldsValue();
        let obj={
            enrollment:{},
            classes:[]
        };
        if(!data.recruitName||!data.start[0]||!data.start[1]||!this.state.choiceClass[0])
        {
            message.warning("请将信息填写完整");
            this.setState({ 
                submitLoad: false,
                choiceClass:this.state.choiceClass
            });
        }
        else{
        obj.enrollment.title=data.recruitName;
        obj.enrollment.startTime=new Date(data.start[0]).getTime()/1000;
        obj.enrollment.endTime=new Date(data.start[1]).getTime()/1000;
        obj.classes=this.state.choiceClass.split(',');
        this.props.dispatch(addRecruit(obj));
        this.setState({ submitLoad: false, visible: false });
       window.location.reload();
        }
    }

    /**
     * 获取招新数据
     */
    handleGetList = () => {
        this.setState({ loading: true });
        if (this.state.curPage * 5 >= this.state.listTotal) {
            //招新信息数据已经加载完毕
            this.setState({
                isEnough: true
            })
            message.info("加载完毕");
            this.setState({ loading: false });
        }
        else {
            this.props.dispatch(getRecruitList({ page: this.state.curPage + 1, rows: 5 })).then(() => {
                //将新加载的数据加入老数据中
                let _newList = this.state.list;
                for(let i=0;i<this.props.recruitList.pagingList.length;i++)
                {
                    _newList.push(this.props.recruitList.pagingList[i]);
                }
                this.setState({
                    list: _newList,
                    listTotal: this.props.recruitList.total,
                    curPage: this.state.curPage + 1
                })
            });
            this.setState({ loading: false });
        }
    }



    /**
     * 全选功能
     */
    handleAllChoice = () => {
        let choiceName = document.getElementsByName('recruitCheck');
        let _choiceLen = choiceName.length;
        let choiceBtn = document.querySelector('.choiceBtn');

        if (choiceBtn.checked === true) {
            for (let i = 0; i < _choiceLen; i++) {
                choiceName[i].checked = true;
            }
        } else {
            for (let i = 0; i < _choiceLen; i++) {
                choiceName[i].checked = false;
            }
        }
    }

    handleChoice=()=>{
        let choiceName=document.getElementsByName('recruitCheck');
        let _choiceLen=choiceName.length;
        let _newArr=[];
        for(let i=0;i<_choiceLen;i++)
        {
            if(choiceName[i].checked===true)
            {
                _newArr.push(choiceName[i].value);
            }
        }
        this.setState({
            deleteArr:_newArr
        })
        this.handleDelete(_newArr);

    }

    handleDelete=(deleteArr)=>{

        this.props.dispatch(deleteRecruitList({ids:deleteArr.join(',')})).then(()=>{
            message.success("删除成功！");
            let choiceName=document.getElementsByName('recruitCheck');
            let _choiceLen=choiceName.length;
            for(let i=0;i<_choiceLen;i++)
            {
                choiceName[i].checked=false;
            }
            window.location.reload();
        });
    }
    /**
     * 下拉框内容改变
     */
    handleChange=(value)=> {
        this.setState({
            choiceClass:`${value}`
        }) 
    }
    handleChange2=(value)=> {
        this.setState({
            choiceClass2:`${value}`
        }) 
    }

    /**
     * 时间的判断
     */
    outTime=(startTime,endTime)=>
    {
        let nowTime=Date.now();
        if(endTime*1000>=nowTime&&startTime*1000<=nowTime)
        {
            return false;
        }
        return true;
    }
    //后期需要删除
    changeState=()=>{
        this.setState({
            isStu:!this.state.isStu
        })
    }
    render() {
        const { visible, submitLoad,visible2, submitLoad2 } = this.state;
        const {getFieldDecorator}=this.props.form;

        return (
            <div className="recruitlist-container">
               
                {!this.state.isStu?<div className="adddel">
                <Popconfirm
                                placement="top"
                                title={`您确定删除选中的信息？`}
                                onConfirm={this.handleChoice}
                                okText="Yes"
                                cancelText="No"
                            >
                    <Button size="small" type="danger">删除</Button>
                    </Popconfirm>
                    <Button size="small" onClick={this.showModal}>添加</Button>
                    {!this.state.isTeacher?"":<Button onClick={this.changeState} size="small" className="changeState">切换状态</Button>}
                    <div className="allCheck" onClick={this.handleAllChoice}>
                        全选：<input className="choiceBtn" type="checkbox" />
                    </div>
                </div>:<>{!this.state.isTeacher?"":<Button onClick={this.changeState} size="small" className="changeState">切换状态</Button>}</>}
               
                <ul className="recruitlist-container-list">
                    {
                        this.state.isStu? this.state.list.map((item, index) => {
                            return <li key={index}>
                                <i className="iconfont li-left" style={{ fontSize: 30 }}>&#xe6c1;</i>
                                <div className="li-left li-title">{item.enrollment.title}</div>
                                <div className="li-left li-time">
                                    <div>开始时间：{timeFormat(item.enrollment.startTime)}</div>
                                    <div>结束时间：{timeFormat(item.enrollment.endTime)}</div>
                                </div>
                                <div className="li-left li-btn">
                                    {
                                        item.isSigned? <Link to={'/enroll/UserHome/'+item.enrollment.id}><Button ghost type="primary">查看</Button></Link>:<Link to={'/enroll/recruit/'+item.enrollment.id}>
                                        <Button disabled={this.outTime(item.enrollment.startTime,item.enrollment.endTime)?'disabled':''}>报名</Button></Link>
                                    }
                               </div>
                            </li>
                        }):this.state.list.map((item, index) => {
                            return <li key={index}>
                            <i className="iconfont li-left li-icon" style={{ fontSize: '3vw' }}>&#xe6c1;</i>
                            <div className="li-left checkbox">
                                <input  name="recruitCheck" type="checkbox" value={item.enrollment.id} />
                            </div>
                            <div className="li-left li-title">{item.enrollment.title}<span style={{fontSize:10}}><Link  to={'/enroll/displaydata/'+item.enrollment.id}>（查看数据）</Link></span></div>
                            <div className="li-left li-time">
                                <div>开始时间：{timeFormat(item.enrollment.startTime)}</div>
                                <div>结束时间：{timeFormat(item.enrollment.endTime)}</div>
                            </div>
                            <div className="li-left li-set">
                                <div className="set-action">
                                    <Button className="set-action-btn" size='small' type="primary" onClick={()=>this.showModal2(item)}>修改</Button>
                                </div>
                                <div className="set-action">
                                <Popconfirm
                                placement="rightTop"
                                title={`您确定删除这条信息？`}
                                onConfirm={()=>this.handleDelete([item.enrollment.id])}
                                okText="Yes"
                                cancelText="No"
                            >
                                    <Button 
                                    className="set-action-btn" 
                                    size='small' type="danger" >
                                        删除
                                    </Button>
                                    </Popconfirm>
                                </div>
                            </div>
                        </li>
                        })
                    }
                </ul>
                {
                    this.state.isEnough ? <div className="recruitlist-nomore">已经到底部了哦！</div> 
                    :<div className="more-btn">
                        <Button 
                        className="recruitlist-lookmore" 
                        type="primary" 
                        loading={this.state.loading} 
                        onClick={this.handleGetList}>
                        查看更多
                    </Button></div>
                }
                <div>
                    <Modal
                        visible={visible}
                        title="添加招新信息"
                        onOk={this.handleSubmit}
                        onCancel={this.handleCancel}
                        footer={[
                            <Button key="back" onClick={this.handleCancel}>
                            Return
                            </Button>,
                            <Button key="submit" type="primary" loading={submitLoad} onClick={this.handleSubmit}>
                            Submit
                            </Button>,
                        ]}
                    >
                    <Form layout="horizontal">
                    <FormItem label="招新标题：">
                        {
                            getFieldDecorator('recruitName')
                            (<Input placeholder={"请输入招新标题"}/>)
                        }
                    </FormItem>

                    <FormItem label="开始日期：">
                        {
                            getFieldDecorator('start',{
                                initialValue:"",
                            })
                            ( <RangePicker
                                showTime={{ format: 'HH:mm' }}
                                format="YYYY-MM-DD HH:mm"
                                placeholder={['Start Time', 'End Time']}
                                onOk={this.onOk}
                            />)
                        }
                    </FormItem>
                    <FormItem label="班级添加（添加招新之后不能修改此处哦）：">
                    <Select
                        mode="tags"
                        style={{ width: '100%' }}
                        placeholder="请在此处填写要添加的班级名称，可添加多个"
                        defaultValue={[]}
                        onChange={this.handleChange}
                    >
                    </Select>
                    </FormItem>
                    </Form>
                    </Modal>
                </div>
                <div>
                    <Modal
                        visible={visible2}
                        title="修改招新信息"
                        onOk={this.handleOk2}
                        onCancel={this.handleCancel2}
                        footer={[
                            <Button key="back" onClick={this.handleCancel2}>
                            Return
                            </Button>,
                            <Button key="submit" type="primary" loading={submitLoad2} onClick={this.handleOk2}>
                            Submit
                            </Button>,
                        ]}
                    >
                    <Form layout="horizontal">
                    <FormItem label="招新标题：">
                        {
                            getFieldDecorator('recruitName2',{
                                initialValue:this.state.item2.enrollment.title
                            })
                            (<Input placeholder={"请输入招新标题"}/>)
                        }
                    </FormItem>

                    <FormItem label="开始日期：">
                        {
                            getFieldDecorator('start2',{
                                initialValue:"",
                            })
                            ( <RangePicker
                                showTime={{ format: 'HH:mm' }}
                                format="YYYY-MM-DD HH:mm"
                                placeholder={['Start Time', 'End Time']}
                                onOk={this.onOk}
                            />)
                        }
                    </FormItem>
                    </Form>
                    </Modal>
                </div>
            </div>
        )
    }
}
export default Form.create()(Recruitlist);